import type { Directive, DirectiveBinding } from "vue";

import { useUserStore } from "@/store";

export const hasPerm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const requiredPerms = binding.value;

    if (!requiredPerms || (typeof requiredPerms !== "string" && !Array.isArray(requiredPerms))) {
      throw new Error(
        "eg：v-has-perm=\"'sys:user:add'\" or v-has-perm=\"['sys:user:add', 'sys:user:edit']\""
      );
    }

    const { roles, perms } = useUserStore().userInfo;
    if (roles?.includes("ROOT")) {
      return;
    }

    const hasAuth = Array.isArray(requiredPerms)
      ? requiredPerms.some((perm) => perms?.includes(perm))
      : perms?.includes(requiredPerms);

    if (!hasAuth && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  },
};

export const hasRole: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const requiredRoles = binding.value;

    if (!requiredRoles || (typeof requiredRoles !== "string" && !Array.isArray(requiredRoles))) {
      throw new Error("eg：v-has-role=\"'ADMIN'\" or v-has-role=\"['ADMIN', 'TEST']\"");
    }

    const { roles } = useUserStore().userInfo;

    const hasAuth = Array.isArray(requiredRoles)
      ? requiredRoles.some((role) => roles?.includes(role))
      : roles?.includes(requiredRoles);

    if (!hasAuth && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  },
};
